import com.alibaba.druid.pool.DruidConnectionHolder;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.pool.ExceptionSorter;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 几行代码轻松复现druid连接泄露的BUG之onFatalError
 * <p>
 * 代码来源: https://heapdump.cn/article/6667879
 */
public class DruidAbandonedCase4OnFatalError {
    public static void main(String[] args) throws Exception {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false");

        dataSource.setMinIdle(2);
        // 保证不会触发DestroyTask，以便手动调用shrink
        dataSource.setTimeBetweenEvictionRunsMillis(1 * 60 * 60 * 1000);
        dataSource.setMinEvictableIdleTimeMillis(0);
        // 用来mock出现FatalError的数据库异常
        dataSource.setExceptionSorter(new MockExceptionSorter());
        dataSource.init();

        // connectioin1为正常的连接
        DruidPooledConnection connection1 = dataSource.getConnection();
        DruidConnectionHolder holder1 = connection1.getConnectionHolder();
        System.out.println(holder1.getConnectionId());

        // connectioin2是数据库操作出现异常的连接
        DruidPooledConnection connection2 = dataSource.getConnection();
        DruidConnectionHolder holder2 = connection2.getConnectionHolder();
        System.out.println(holder2.getConnectionId());
        // 数据库操作出现FatalError
        fatalError(connection2);
        connection2.close();

        // connectioin3是正常的连接
        DruidPooledConnection connection3 = dataSource.getConnection();
        DruidConnectionHolder holder3 = connection3.getConnectionHolder();
        System.out.println(holder3.getConnectionId());
        connection3.close();

        connection1.close();

        System.out.println();
        System.out.println("调用shrink【之前】，连接池中连接情况,begin");
        List<Map<String, Object>> conns = dataSource.getPoolingConnectionInfo();
        for (Map<String, Object> conn : conns) {
            System.out.println(conn.get("connectionId"));
        }
        System.out.println("调用shrink【之前】，连接池中连接情况,end");

        // 手动执行shrink
        dataSource.shrink(true);

        System.out.println();
        System.out.println("调用shrink【之后】，连接池中连接情况,begin");
        conns = dataSource.getPoolingConnectionInfo();
        for (Map<String, Object> conn : conns) {
            System.out.println(conn.get("connectionId"));
        }
        System.out.println("调用shrink【之后】，连接池中连接情况,end");

        System.out.println();
        System.out.println(holder1.getConnectionId() + " isClosed:" + holder1.getConnection().isClosed());
        System.out.println(holder2.getConnectionId() + " isClosed:" + holder2.getConnection().isClosed());
        System.out.println(holder3.getConnectionId() + " isClosed:" + holder3.getConnection().isClosed());
    }

    private static void fatalError(Connection conn) {
        Statement pstmt = null;
        ResultSet rs = null;
        try {
            String sql = "select * from unExistTable";
            pstmt = conn.createStatement();
            rs = pstmt.executeQuery(sql);

            while (rs.next()) {
                int id = rs.getInt("id");
                System.out.println("id: " + id);
            }
        } catch (SQLException e) {
            // e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (pstmt != null) {
                    pstmt.close();
                }
            } catch (SQLException e) {
                // e.printStackTrace();
            }
        }
    }

    static class MockExceptionSorter implements ExceptionSorter {
        @Override
        public boolean isExceptionFatal(SQLException e) {
            return true;
        }

        @Override
        public void configFromProperties(Properties properties) {
        }
    }
}